<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      @submit.native.prevent
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input
          v-model="queryParams.equipmentName"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="20">
      <el-col :span="5" style="padding-right: 0 !important">
        <left-tree
          @getParentId="getParentIdFunc"
          @cateChange="cateChange"
          ref="leftRef"
        />
      </el-col>
      <el-col :span="19" style="padding-left: 10 !important">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['equipment:info:add']"
              >新增</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['equipment:info:edit']"
              >修改</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-s-tools"
              size="mini"
              :disabled="single"
              @click="handleParams"
              v-hasPermi="['equipment:param:edit']"
              >参数配置</el-button
            >
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button
              type="danger"
              plain
              icon="el-icon-warning"
              size="mini"
              :disabled="single"
              @click="handleDisable"
              v-hasPermi="['equipment:info:disable']"
              >停用设备</el-button
            >
          </el-col> -->
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-delete"
              size="mini"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['equipment:info:remove']"
              >删除</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="primary"
              icon="el-icon-download"
              size="mini"
              :loading="btnLoading"
              @click="handleExport"
              v-hasPermi="['equipment:info:export']"
              >导出</el-button
            >
          </el-col>
        </el-row>

        <el-table
          :cell-style="{ padding: this.tablePadding }"
          border
          v-loading="loading"
          :data="infoList"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="getInfoItem"
          height="300"
        >
          <el-table-column type="selection" width="55" align="center" />
          <!-- <el-table-column label="设备ID" align="center" prop="equipmentId" /> -->
          <el-table-column
            label="设备名称"
            align="center"
            prop="equipmentName"
          />
          <el-table-column label="状态" align="center" prop="status">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column
            label="设备分类"
            align="center"
            prop="equipmentCategoryName"
          />
          <el-table-column
            label="责任人"
            align="center"
            prop="responseManName"
          />
          <el-table-column label="供应商" align="center" prop="supplierName" />
          <el-table-column label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                v-hasPermi="['equipment:info:edit']"
                >修改</el-button
              >
              <el-button
                size="mini"
                type="text"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                v-hasPermi="['equipment:info:remove']"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          :page.sync="queryParams.pageNum"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
        <!-- 设备信息 -->
        <el-tabs v-model="activeName">
          <el-tab-pane label="设备详细信息" name="detailsName">
            <equipment-details
              :details="details"
              :realTimeObj="realTimeObj"
              v-show="Object.keys(details).length !== 0"
            />

            <div v-show="Object.keys(details).length === 0" class="no-data-txt">
              暂无数据
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 添加或修改设备信息对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="730px" append-to-body>
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        :rules="rules"
        layout="inline"
        label-width="120px"
      >
        <el-form-item label="状态">
          <div style="width: 208px">
            <el-radio-group v-model="form.status">
              <el-radio
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="parseInt(dict.dictValue)"
                >{{ dict.dictLabel }}</el-radio
              >
            </el-radio-group>
          </div>
        </el-form-item>

        <el-form-item label="设备分类" prop="equipmentCategoryId">
          <div style="width: 208px">
            <treeselect
              v-model="form.equipmentCategoryId"
              :options="categoryList"
              :normalizer="normalizer"
              :show-count="true"
              placeholder="选择设备分类"
            />
          </div>
        </el-form-item>
        <el-form-item label="名称" prop="equipmentName">
          <el-input v-model="form.equipmentName" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="责任人" prop="responseManId">
          <div class="input-width">
            <el-select v-model="form.responseManId" placeholder="请选择责任人">
              <el-option
                v-for="item in responseManOptions"
                :key="item.userId"
                :label="item.userName"
                :value="item.userId"
                :disabled="item.status == 1"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="规格型号">
          <el-input v-model="form.type" placeholder="请输入规格型号" />
        </el-form-item>

        <el-form-item label="供应商" prop="supplierId">
          <div class="input-width">
            <el-select v-model="form.supplierId" placeholder="请输入供应商">
              <el-option
                v-for="item in supplierOptions"
                :key="item.supplierId"
                :label="item.supplierName"
                :value="item.supplierId"
              />
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="生产日期" prop="productDate">
          <div class="input-width" style="width: 207px">
            <el-date-picker
              clearable
              v-model="form.productDate"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="选择生产日期"
            ></el-date-picker>
          </div>
        </el-form-item>
        <el-form-item label="维护周期(天)" prop="lifeSpan">
          <el-input v-model="form.lifeSpan" placeholder="请输入维护周期(天)" />
        </el-form-item>
        <el-form-item label="设备金额(万元)" prop="money">
          <el-input v-model="form.money" placeholder="请输入设备金额" />
        </el-form-item>
        <el-form-item label="设备编号" prop="address">
          <el-input v-model="form.address" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="设备IP" prop="equipmentIp">
          <el-input v-model="form.equipmentIp" placeholder="请输入设备IP" />
        </el-form-item>
        <!-- <el-form-item label="通信插件" prop="equipmentPluginId">
          <div class="input-width">
            <el-select v-model="form.equipmentPluginId" placeholder="请选择通信插件">
              <el-option
                v-for="item in optionsPlugin"
                :key="item.equipmentPluginId"
                :label="item.name"
                :value="item.equipmentPluginId"
              />
            </el-select>
          </div>
        </el-form-item> -->
        <el-form-item label="额定功率">
          <el-input v-model="form.ratedPower" placeholder="请输入额定功率" />
        </el-form-item>

        <el-form-item label="出厂编号" prop="factoryNumber">
          <el-input v-model="form.factoryNumber" placeholder="请输入出厂编号" />
        </el-form-item>
        <el-form-item label="增材方式" prop="materialAddMethodId">
          <div class="input-width">
            <el-select
              v-model="form.materialAddMethodId"
              placeholder="请选择增材方式"
            >
              <el-option
                v-for="dict in technologyMaterialAddMethodOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="parseInt(dict.dictValue)"
                :disabled="dict.status == 1"
              >
                <span style="float: left">{{ dict.dictDataAbbreviation }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{
                  dict.dictLabel
                }}</span>
              </el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="model-textarea">
          <el-input
            type="textarea"
            v-model="form.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="设备照片" style="width: 328px">
          <image-upload :value="form.imageUrl" @setValue="setImageUrl" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          :loading="btnLoading"
          v-funThrottle="[submitForm]"
          >确 定</el-button
        >
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
  getResponseManOptions,
  updateEquipmentStatus,
} from "@/api/equipment/info";
// import {getOptionsPlugin} from "@/api/equipment/plugin"
import { listCategory } from "@/api/equipment/category";
import { getSupplierOption } from "@/api/base/supplier";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import LeftTree from "./components/Left.vue";
import EquipmentDetails from "./components/NDetails.vue";
import ImageUpload from "@/components/ImageUpload";
import socket from "../../../websocketMixins";
export default {
  name: "Info",
  components: { LeftTree, EquipmentDetails, Treeselect, ImageUpload },
  mixins: [socket],
  data() {
    var testIP = (rule, value, callback) => {
      if(value==null||value==''){
        return callback(new Error("设备IP不能为空"));
      }
      const regIP =
        /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      if (regIP.test(value)) {
        return callback();
      }
      return callback(new Error("请输入正确的IP格式"));
    };
    return {
      // 遮罩层
      loading: true,
      btnLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备信息表格数据
      infoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      activeName: "detailsName",
      // 状态字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        equipmentCategoryId: null,
        equipmentName: null,
        responseManId: null,
        status: null,
      },
      selectNames: [],
      responseManOptions: [],
      supplierOptions: [],
      categoryList: [], //分类树型
      // 表单参数
      form: {},
      technologyMaterialAddMethodOptions: [], //增材方式option
      details: {},
      // 表单校验
      rules: {
        equipmentCategoryId: [
          { required: true, message: "设备分类不能为空", trigger: "change" },
        ],
        equipmentName: [
          { required: true, message: "名称不能为空", trigger: "blur" },
        ],
        equipmentPluginId: [
          { required: true, message: "通信插件不能为空", trigger: "blur" },
        ],
        materialAddMethodId: [
          { required: true, message: "增材方式不能为空", trigger: "blur" },
        ],
        responseManId: [
          { required: true, message: "责任人不能为空", trigger: "blur" },
        ],
        supplierId: [
          { required: true, message: "供应商不能为空", trigger: "blur" },
        ],
        equipmentIp: [
          {required: true, trigger: "blur", validator: testIP },
        ],
        address: [
          { required: true, message: "设备编号不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
      },
      realTimeObj: {},
      address: "", //当前设备address
      optionsPlugin: [],
    };
  },
  created() {
    this.getResponseManOptions();
    this.getSulipperOptions();
    // getOptionsPlugin().then(res=>{
    //   this.optionsPlugin=res.data
    // })
    this.getTechnologyMaterialAddMethodOption();
    this.getDicts("equipment_info_type").then((response) => {
      this.statusOptions = response.data;
    });
  },
  mounted() {
    this.initWebSocket();
  },
  watch: {
    $route: {
      handler: function (route) {
        this.queryParams.equipmentId = route.query.equipmentId;
        this.queryParams.equipmentName = route.query.equipmentName;
        this.$nextTick(() => {
          this.queryParams.equipmentCategoryId =
            this.$refs.leftRef.firstCategoryId;
        });
        this.getList();
      },
      immediate: true,
    },
  },
  methods: {
    websocketonmessage(msg) {
      //数据接收
      let obj = msg.data;
      if (obj.indexOf("room") !== -1) {
        let res = JSON.parse(obj);
        if (res.room == 3 && res.id == this.address) {
          this.realTimeObj = res;
        }
      }
      this.reset();
    },
    // 用户状态修改
    handleStatusChange(row) {
      let text = row.status == 1 ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.equipmentName + '"设备吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",closeOnClickModal:false,
          type: "warning",
        }
      )
        .then(function () {
          return updateEquipmentStatus({
            equipmentId: row.equipmentId,
            status: row.status,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status == 0? 1 : 0;
        });
    },
    setImageUrl(url) {
      this.form.imageUrl = url;
    },
    getTechnologyMaterialAddMethodOption() {
      this.getDicts("base_material_addMethod").then((response) => {
        this.technologyMaterialAddMethodOptions = response.data;
      });
    },
    getParentIdFunc(len, id) {
      if (len > 0) {
        this.queryParams.equipmentCategoryId = id;

        this.handleQuery();
      } else {
        this.loading = false;
      }
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.equipmentCategoryId,
        label: node.equipmentCategoryName,
        children: node.children,
      };
    },
    cateChange() {
      //分类有修改
      this.getCategoryList();
    },
    /* 获取设备分类列表 */
    getCategoryList() {
      listCategory().then((response) => {
        this.categoryList = response.data;
      });
    },
    getSulipperOptions() {
      getSupplierOption().then((response) => {
        this.supplierOptions = response.data;
        this.loading = false;
      });
    },
    /**获取用户列表 */
    getResponseManOptions() {
      getResponseManOptions().then((response) => {
        this.responseManOptions = response.rows;
        this.loading = false;
      });
    },

    /** 查询设备信息列表 */
    getList() {
      this.loading = true;
      listInfo(this.queryParams).then((response) => {
        this.infoList = response.rows;
        // if (this.infoList.length > 0) {
        //    this.getInfoItem(this.infoList[0]);
        // } else {
        this.details = {};
        // }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 状态字典翻译
    statusFormat(row, column) {
      let status = this.selectDictLabel(this.statusOptions, row.status);
      if (status == null || status == "") {
        status = "已停用";
      }
      return status;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.resetModel();
    },
    // 表单重置
    resetModel() {
      this.form = {
        equipmentId: null,
        equipmentCategoryId: null,
        equipmentName: null,
        responseManId: null,
        imageUrl: null,
        type: null,
        factoryNumber: null,
        supplierId: null,
        productDate: null,
        lifeSpan: null,
        equipmentPluginId: null,
        money: null,
        address: null,
        ratedPower: null,
        status: 0,
        startTime: null,
        equipmentIp: null,
        endTime: null,
        remark: null,
        materialAddMethodId: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.equipmentId = "";
      this.resetForm("queryForm");
      this.queryParams.equipmentName = "";
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.equipmentId);
      this.selectNames = selection.map((item) => item.equipmentName);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetModel();
      this.form.equipmentCategoryId = this.queryParams.equipmentCategoryId;
      this.open = true;
      this.title = "添加设备信息";
    },
    getInfoItem(row) {
      this.resetModel();
      const equipmentId = row.equipmentId || this.ids;
      if (row.equipmentId) {
        //如果是点击行，拿设备resetSocket实时数据
        this.address = row.address; //保存当前设备address
        this.websocketsend(row.address);
      }
      getInfo(equipmentId).then((response) => {
        this.details = response.data;
        [
          "oxygen",
          "cabinPressure",
          "filterPressureDiff",
          "fanFlux",
          "buildCylinderTemperature",
          "fanPipeTemp",
        ].forEach((key) => {
          if (key in this.details) {
            this.realTimeObj[key] = this.details[key];
          }
        });
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetModel();
      const equipmentId = row.equipmentId || this.ids;
      getInfo(equipmentId).then((response) => {
        this.form = response.data;
        this.form.updateBy = null;
        this.form.updateTime = null;
        this.open = true;
        this.title = "修改设备信息";
      });
    },
    handleParams() {
      let id = this.ids[0];
      let item = this.infoList.filter((item) => {
        return item.equipmentId == id;
      });
      this.$router.push({
        path: "/equipment/param",
        query: { equipmentId: id, equipmentName: item[0].equipmentName },
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          if (this.form.equipmentId != null) {
            updateInfo(this.form)
              .then((response) => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
                this.btnLoading = false;
              })
              .catch(() => {
                this.btnLoading = false;
              });
          } else {
            addInfo(this.form)
              .then((response) => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.btnLoading = false;
                // 设置新增数据时选中的节点，重显到tree上
                this.$refs.leftRef.setNodeId(this.form.equipmentCategoryId);
              })
              .catch(() => {
                this.btnLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const equipmentIds = row.equipmentId || this.ids;
      const name = row.equipmentName || this.selectNames;
      this.$confirm(
        '是否确认删除设备名称为"' +
          name +
          '"的数据项? 删除设备可能会导致相关联数据被删除',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",closeOnClickModal:false,
          type: "warning",
        }
      )
        .then(function () {
          return delInfo(equipmentIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.btnLoading = true;
      this.download(
        "equipment/info/export",
        {
          ...this.queryParams,
        },
        `equipment_info.xlsx`,
        "",
        () => {
          this.btnLoading = false;
        }
      );
    },
  },
};
</script>
<style lang="scss"  scoped>
.model-textarea {
  ::v-deep .el-textarea__inner {
    width: 208px !important;
  }
}
</style>
